package com.adv.ems.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONUtil;
import com.adv.ems.db.entity.EnergyReportTemplateDO;
import com.adv.ems.manager.EnergyReportTemplateManager;
import com.adv.ems.model.dto.APIResponse;
import com.adv.ems.model.param.BaseQueryParam;
import com.adv.ems.model.vo.ReportTemplateVO;
import com.adv.ems.service.ReportTemplateService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class ReportTemplateServiceImpl implements ReportTemplateService {
    @Resource
    EnergyReportTemplateManager energyReportTemplateManager;

    @Override
    public ReportTemplateVO list(BaseQueryParam content, String acceptLanguage) {
        List<ReportTemplateVO.Info> collect = energyReportTemplateManager
                .getAllMap()
                .values()
                .stream()
                .sorted(Comparator.comparing(EnergyReportTemplateDO::getCreateTime).reversed())
                .filter(i -> !StringUtils.hasLength(content.getKeyword()) || i.getName().contains(content.getKeyword()))
                .map(ReportTemplateVO.Info::new)
                .collect(Collectors.toList());
        ReportTemplateVO vo = new ReportTemplateVO();
        vo.setList(collect);
        return vo;
    }

    @Override
    public Boolean update(MultipartFile file, String name, String acceptLanguage) {
        EnergyReportTemplateDO energyReportDO = new EnergyReportTemplateDO();
        String fileName = file.getOriginalFilename();
        try {
            byte[] bytes = IoUtil.readBytes(file.getInputStream());
            energyReportDO.setName(name == null || name.trim().equals("null") ? fileName : name);
            energyReportDO.setFileName(fileName);
            energyReportDO.setData(bytes);
            energyReportDO.setCreateTime(new Date());
            energyReportDO.setUpdateTime(new Date());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        energyReportTemplateManager.saveOrUpdateData(energyReportDO);
        return true;
    }

    @Override
    public void downloadFile(Long id, HttpServletResponse response) {
        try {
            Optional<EnergyReportTemplateDO> first = energyReportTemplateManager.getAllMap().values().stream().filter(r -> r.getId().equals(id)).findFirst();
            if (!first.isPresent() || first.get().getData() == null) {
                APIResponse<Object> rsp = new APIResponse<>();
                rsp.setCode(500);
                rsp.setMsg("文件不存在");
                response.getWriter().write(JSONUtil.toJsonStr(rsp));
                return;
            }
            EnergyReportTemplateDO reportDO = first.get();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + reportDO.getFileName() + "\"");
            response.setHeader("Content-Type", "application/octet-stream");
            response.setHeader("Content-Length", String.valueOf(reportDO.getData().length));
            response.getOutputStream().write(reportDO.getData());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Boolean delete(Long id) {
        energyReportTemplateManager.removeById(id);
        return true;
    }
}
